/**
 * Created by huanggw on 2015/10/23.
 */
var array = document.getElementById("array"); //箭头
var listC = document.getElementById("listContainer");
var toggle = document.getElementById("switch");
var cur = document.getElementById("current");
var gatelist = document.getElementById("gatelist");
var footer = document.getElementById("footer");
var mapContainer = document.getElementById('mapContainer');
var map2dContainer = document.getElementById("map2d");
var storyContainer = document.getElementById("story");
var commentContainer = document.getElementById("commentContainer");
var commentContent = document.getElementById("commentContent");
var commentSubmit = document.getElementById("commentSubmit");
var like = document.getElementById("like");

toggle.onclick = function() {
    if(document.getElementById("toggle").checked) {
        listC.style.top = "110%";
    }
}

var panorama = new BMap.Panorama('mapContainer');
panorama.setOptions({linksControl: false});
panorama.setOptions({navigationControl: false});

var panoramaService = new BMap.PanoramaService();

function createXMLHttpRequest(){
    var objXMLHttp;
    //对于Firefox,Opera等遵守DOM 2规范的浏览器
    if(window.XMLHttpRequest){
        objXMLHttp = new XMLHttpRequest();
    }
    //对于IE浏览器
    else{
        //将IE浏览器不同的XMLHttp实现声明为数组
        var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
        //依次对每个XMLHttp创建XMLHttpRequest对象
        for(var i = 0; n< MSXML.length; i++){
            try{
                //微软发布的是ActiveX控件
                objXMLHttp = new ActiveXObject(MSXML[i]);
                //如果正常创建XMLHttpRequest对象就使用break跳出循环
                break;
            }catch(e){
                alert("创建XMLHttpRequest对象失败");
            }
        }
    }
    return objXMLHttp;
}

var xhr = createXMLHttpRequest();

//var host = "http://localhost:3000"; 
var host = "http://schoolgate.oschina.mopaasapp.com"

angular.module("schoolgate",['tm.pagination'])
.controller("mainCtrl", function($scope,$timeout) {
        $scope.city = "城市"; //当前城市
        $scope.school = "学校"; //当前学校
        $scope.campus = "校区"; //当前校区
        $scope.gate = "校门"; //当前校门
        $scope.list = [];
        $scope.schoolinfo = null; //当前学校信息
        $scope.campusinfo = null; //当前校区信息
        $scope.gateinfo = null; //当前校门信息
        $scope.schoolselected = 0;
        $scope.campusselected = 0;
        $scope.type = 1; //当前选项
        $scope.id = null; //当前id
        $scope.story = "";
        $scope.commentContent = '';
        $scope.commentsAll = []; //当前校门评论
        $scope.comments = []; //当前页评论

        $scope.like = function(type) { //type=1表示增加一次，type=0表示获取当前喜欢数量
            var url = host+"/like";
            var obj = {
                school: $scope.school,
                campus: $scope.campus,
                gate: $scope.gate,
                type: type
            }
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $timeout(function(){
                            $scope.likenum = JSON.parse(xhr.responseText).likenum;
                            console.log($scope.likenum)
                        }, 10)
                    }
                }
            }
            xhr.send(JSON.stringify(obj));
        }

        $scope.commentSubmit = function() {
            if(!$scope.commentContent) {alert("请输入评论！"); return;}
            var url = host+"/comment";
            var obj = {
                school: $scope.school,
                campus: $scope.campus,
                gate: $scope.gate,
                comment: $scope.commentContent
            }
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            //http://schoolgate.oschina.mopaasapp.com/
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $timeout(function(){
                            $scope.commentsAll = JSON.parse(xhr.responseText);
                            var page = Math.ceil($scope.commentsAll.length/$scope.conf.itemsPerPage)
                            $scope.setPagination($scope.commentsAll.length, page);
                            $scope.commentContent = '';
                        },20)
                    }
                    else {
                        
                    }
                }
            }
            xhr.send(JSON.stringify(obj));
        }


        $scope.getComment = function() {
            var url = host+"/comment/?school="+$scope.school+"&campus="+$scope.campus+"&gate="+$scope.gate;
            xhr.open("GET", url, true);
            //http://schoolgate.oschina.mopaasapp.com/
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $timeout(function(){
                                $scope.commentsAll = JSON.parse(xhr.responseText);
                                //console.log($scope.comments)
                                //需要加入判断当前查询校门是否有改变
                                $scope.setPagination($scope.commentsAll.length, 1);
                                $scope.getCommentByPage(1);
                                $scope.like(0);
                            }, 50
                        )
                    }
                }
            }
            xhr.send();
        }

        $scope.getCommentByPage = function (page) {
            var start = (page-1)*15;
            var end = page*15;
            if(page == $scope.paginationConf.numberOfPages) {
                end = $scope.commentsAll.length;
            }
            $scope.comments = $scope.commentsAll.slice(start, end);
        }

        $scope.setPagination = function(total, page) {
            //pagination
            $scope.paginationConf = {
                currentPage: page,
                totalItems: total,
                itemsPerPage: 15,
                pagesLength: 5,
                perPageOptions: [10, 20, 30, 40, 50],
                onChange: function(){
                    $scope.getCommentByPage($scope.paginationConf.currentPage)
                }
            };
        }

        $scope.getCityInfo  = function() {
            var url = host+"/getinfo/?citylist=1"
            xhr.open("GET", url, true);
            //http://schoolgate.oschina.mopaasapp.com/
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $scope.list = [];
                        var data = JSON.parse(xhr.responseText).city
                        console.log(data);
                        $timeout(function(){
                            for(var i = 0; i < data.length; i++) {
                                $scope.list.push({"name": data[i].name});
                                //$scope.setVal(0); //设定为第一个城市
                            }
                            //$scope.getSchoolInfo();
                            }, 50
                        )
                    }
                }
            }
            xhr.send();
        }
        $scope.setCity = function() {
            $scope.type = 1;
            $scope.getCityInfo();
            //设置箭头位置
            array.style.left = "calc(50% - 160px)";
            listC.style.top = "76px";
        }

        $scope.getSchoolInfo = function() {
            var url = host+"/getinfo/?city="+$scope.city;
            xhr.open("GET", url, true); //getinfo?num=32&num1=13&type=add
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        $scope.list = [];
                        //获取信息初始化
                        $scope.schoolinfo = JSON.parse(xhr.responseText);
                        $scope.school = $scope.schoolinfo[0].name;
                        $scope.story = "";

                        $timeout(function(){
                            for(var i = 0; i < $scope.schoolinfo.length; i++) {
                                $scope.list.push({"name": $scope.schoolinfo[i].name});
                                //$scope.setVal(0);
                            }}, 50
                        )
                    }
                }
            }
            xhr.send();
        }
        $scope.setSchool = function() {
            $scope.type = 2;
            $scope.getSchoolInfo();
            //设置箭头位置
            array.style.left = "calc(50% - 60px)";
            listC.style.top = "76px";
        }

        $scope.getCampusInfo = function() {
            $scope.list = [];
            var data = $scope.schoolinfo[$scope.schoolselected].info;
            $scope.campusinfo = data;
            $timeout(function(){
                for(var i = 0; i < data.length; i++) {
                    $scope.list.push({"name": data[i].campus});
                    //$scope.setVal(0);
                }}, 50
            )
        }
        $scope.setCampus = function() {
            $scope.type = 3;
            $scope.getCampusInfo();
            //设置箭头位置
            array.style.left = "calc(50% + 40px)";
            listC.style.top = "76px";
        }

        $scope.getGateInfo = function() {
            $scope.list = [];
            var data = $scope.schoolinfo[$scope.schoolselected].info[$scope.campusselected].gates;
            $scope.gateinfo = data;
            //console.log( $scope.gateinfo);
            $timeout(function(){
                for(var i = 0; i < data.length; i++) {
                    $scope.list.push({"name": data[i].name});
                }}, 50
            )
        }
        $scope.setGate = function() {
            $scope.type = 4;
            $scope.getGateInfo();
            //设置箭头位置
            array.style.left = "calc(50% + 140px)";
            listC.style.top = "76px";
        }

        $scope.setVal = function(num) {
            if($scope.type == 1) {
                $scope.city = $scope.list[num].name;
                //$scope.getSchoolInfo();
            }
            else if($scope.type == 2){
                $scope.school = $scope.list[num].name;
                $scope.schoolselected = num;
                //$scope.getCampus();
            }
            else if($scope.type == 3){
                $scope.campus = $scope.list[num].name;
                $scope.campusselected = num;
                //$scope.getGate();
            }
            else if($scope.type == 4){
                $scope.gate = $scope.gateinfo[num].name;
                listC.style.top = "110%";
                toggle.checked = false;
                if($scope.gateinfo[num].alsoname) {
                    $scope.current = $scope.school+$scope.campus+$scope.gate+"("+$scope.gateinfo[num].alsoname+")";
                }
                else {
                    $scope.current = $scope.school+$scope.campus+$scope.gate
                }
                if($scope.gateinfo[num].story) {
                    $scope.story = $scope.gateinfo[num].story;
                    storyContainer.style.left = "20px";
                    $timeout(function() {
                        storyContainer.style.left = "-300px";
                    }, 30000);
                }
                else {
                    storyContainer.style.left = "-300px";
                }
                $scope.setView($scope.gateinfo[num].id, $scope.gateinfo[num].heading,
                    $scope.gateinfo[num].pitch, $scope.gateinfo[num].zoom);
                //更换id
                //$scope.id = $scope.gateinfo[num].id;

                //评论
                $scope.getComment();
            }
        }

        $scope.setValDirect = function(num) {
            //直接设置
            $scope.type = 4;
            $scope.setVal(num);
        }

        //var tanslateCallback =
        $scope.setView = function(id, heading, pitch) {
            //2维地图
            panoramaService.getPanoramaById(id, function(data) {
                //console.log(data.position);
                var point = new BMap.Point(data.position.lng, data.position.lat);
                var map = new BMap.Map("map2d",{minZoom:10,maxZoom:25});
                map.centerAndZoom(point, 18);
                var marker = new BMap.Marker(point);
                map.addOverlay(marker);
            })
            //全景地图
            panorama.setId(id);
            $timeout(function(){
                panorama.setPov({heading: heading, pitch: pitch, zoom: 1.31});
            },200);
        }

        $scope.confirmTip = function() {
            document.getElementById("tip").style.left = "-400px";
        }

        $scope.geo = function() {
            //定位
            var geolocation = new BMap.Geolocation();
            //逆解析城市名
            var geoc = new BMap.Geocoder();
            geolocation.getCurrentPosition(function(r){
                if(this.getStatus() == BMAP_STATUS_SUCCESS){
                    //console.log('您的位置：'+r.point.lng+','+r.point.lat);
                    var point = new BMap.Point(r.point.lng, r.point.lat);
                    geoc.getLocation(point, function(rs){
                        var addComp = rs.addressComponents;
                        //console.log(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);

                    });
                }
                else {
                    console.log('failed'+this.getStatus());
                }
            },{enableHighAccuracy: true})
        }

        $scope.full = function() {
            if(document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if(document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if(document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen();
            } else if(document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen();
            }
        }

        var _2dview = 0;
        $scope.mapview = function() {
            //$scope._2dview = $scope._2dview == 1? 0 : 1;
            if(_2dview == 0) {
                map2dContainer.style.top = "36px";
                _2dview = 1;
            }else {
                map2dContainer.style.top = "100%";
                _2dview = 0;
            }
        }

        var on = 0;
        $scope.showgatelist = function(num) {
            on = num;
            if(num == 0) {
                //footer.style.borderLeft ="1px solid rgba(100, 100, 100, 0.5)";
            }
            //gatelist.style.right = "104px";
            var n = $scope.gateinfo.length;
            gatelist.style.bottom = "30px";
            gatelist.style.opacity = 1;
            commentContainer.style.bottom = 31*n + 30 + "px";
        }

        $scope.hidegatelist = function() {
            /*if(num == 0) {
                footer.style.background = "rgba(39, 39, 39, 0.3)"
                $timeout(function(){
                    if(on == 1) return false;
                    gatelist.style.bottom = "-400px";
                }, 2000)
            }
            else {
                gatelist.style.bottom = "-400px";
            }*/
            var n = $scope.gateinfo.length;
            gatelist.style.bottom = -31*n + 30 + "px";
            gatelist.style.opacity = 0;
            commentContainer.style.bottom = "30px";
        }

        $scope.hidelistC = function() {
            listC.style.top = "110%";
        }

        var _commentview = 0;
        $scope.commentview = function() {
            if(_commentview == 0) {
                _commentview = 1;
                commentContainer.style.right = "0px";
                commentSubmit.style.right = "7px";
                commentContent.style.right = "7px";

                $scope.getComment();
            }
            else{
                _commentview = 0;
                commentContainer.style.right = "-400px";
                commentSubmit.style.right = "-400px";
                commentContent.style.right = "-400px";
            }
        }

        $scope.hehe = function() {
            console.log("hh")
        }

        //初始化
        $scope.current = "上海交通大学闵行校区东门";
        $scope.city = "上海";;
        $scope.school = "上海交通大学";
        $scope.type = 4;
        $scope.gateinfo = [
            {"name":"东门","id":"01000300001309181348482385D","heading":247,"pitch": 1},
            {"name":"思源门","id":"01000300001309271133460215C","heading":342,"pitch":1},
            {"name":"东南一门","alsoname":"凯旋门","id":"01000300001309201158390965D","heading":343,"pitch":-3},
            {"name":"北一门","id":"01000300001309271053335345C","heading":172,"pitch":-1}
        ];
        //从服务器获取数据
        $scope.getCityInfo();
        $timeout($scope.getSchoolInfo(),10)
        $scope.setView("01000300001309181348482385D", 247, 1, 1.31);
        $scope.campus = "闵行校区";
        $scope.gate = "东门";
        $scope.like(0);
        $scope.geo();
        $scope.setPagination(0);
    })
